package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.mapper.AgencyCertificationMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.dto.AgencyCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 机构认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class AgencyCertificationServiceImpl extends ServiceImpl<AgencyCertificationMapper, AgencyCertification> implements IAgencyCertificationService {
    @Autowired
    private AgencyCertificationAuditMapper agencyCertificationAuditMapper;

    /**
     * 获取机构认证审核驳回原因
     *
     * @return
     */
    @Override
    public AgencyCertificationAuditResDTO showRejectReason() {
        //根据当前用户id 结合 审核状态失败 从认证审核表查询
        Long userId = UserContext.currentUserId();
        LambdaQueryWrapper<AgencyCertificationAudit> wrapper = new LambdaQueryWrapper<AgencyCertificationAudit>()
                .eq(AgencyCertificationAudit::getServeProviderId, userId)
                .eq(AgencyCertificationAudit::getCertificationStatus, CertificationStatusEnum.FAIL.getStatus())
                .orderByDesc(AgencyCertificationAudit::getAuditTime);
        List<AgencyCertificationAudit> agencyCertificationAudits = agencyCertificationAuditMapper.selectList(wrapper);
        if (ObjectUtil.isEmpty(agencyCertificationAudits)){
            return null;
        }
        return BeanUtil.copyProperties(agencyCertificationAudits.get(0), AgencyCertificationAuditResDTO.class);
    }

    /**
     * 机构认证审核
     *
     * @param id
     * @param certificationStatus
     * @param rejectReason
     */
    @Override
    public void review(Long id, Integer certificationStatus, String rejectReason) {
        //查询机构认证信息
        CurrentUserInfo userInfo = UserContext.currentUser();
        //更新机构认证审核表 根据认证申请id 查出申请记录
        AgencyCertificationAudit agencyCertificationAudit = agencyCertificationAuditMapper.selectById(id);
        if (ObjectUtil.isEmpty(agencyCertificationAudit)){
            throw new ForbiddenOperationException("没有查询到数据");
        }
        //更新审核状态、审核人id、审核人name、审核时间、认证状态、拒绝原因
        //设置审核状态 已审核
        agencyCertificationAudit.setAuditStatus(1);
        //设置审核人id
        agencyCertificationAudit.setAuditorId(userInfo.getId());
        //设置审核人name
        agencyCertificationAudit.setAuditorName(userInfo.getName());
        //设置审核时间
        agencyCertificationAudit.setAuditTime(LocalDateTime.now());
        //设置认证状态
        agencyCertificationAudit.setCertificationStatus(certificationStatus);
        if(ObjectUtil.isNotEmpty(rejectReason)){
            //设置拒绝原因
            agencyCertificationAudit.setRejectReason(rejectReason);
        }
        //调用mapper更新
        agencyCertificationAuditMapper.updateById(agencyCertificationAudit);
        //更新服务人员认证信息表 认证时间 认证状态
        //根据认证审核表 获取到服务人员id
        //根据服务人员id 查出认证信息表相关信息
        AgencyCertification agencyCertification = baseMapper.selectById(agencyCertificationAudit.getServeProviderId());
        //设置认证时间
        agencyCertification.setCertificationTime(agencyCertificationAudit.getAuditTime());
        //设置认证状态
        agencyCertification.setCertificationStatus(certificationStatus);
        //调用mapper更新
        baseMapper.updateById(agencyCertification);
    }

    /**
     * 机构认证分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<AgencyCertificationAuditResDTO> getPage(AgencyCertificationAuditPageQueryReqDTO dto) {
        //设置分页参数
        Page<AgencyCertificationAudit> page = PageUtils.parsePageQuery(dto, AgencyCertificationAudit.class);
//        Page<WorkerCertificationAudit> page = PageUtils.parsePageQuery(dto, WorkerCertificationAudit.class);

        //设置分页条件
        LambdaQueryWrapper<AgencyCertificationAudit> wrapper = new LambdaQueryWrapper<AgencyCertificationAudit>()
                .like(ObjectUtil.isNotEmpty(dto.getName()), AgencyCertificationAudit::getName, dto.getName())
                .eq(ObjectUtil.isNotEmpty(dto.getLegalPersonName()), AgencyCertificationAudit::getLegalPersonName, dto.getLegalPersonName())
                .eq(ObjectUtil.isNotEmpty(dto.getAuditStatus()), AgencyCertificationAudit::getAuditStatus, dto.getAuditStatus())
                .eq(ObjectUtil.isNotEmpty(dto.getCertificationStatus()), AgencyCertificationAudit::getCertificationStatus, dto.getCertificationStatus());
        //分页查询
        Page<AgencyCertificationAudit> list = agencyCertificationAuditMapper.selectPage(page, wrapper);
        if (ObjectUtil.isNull(list.getRecords())){
            throw new ForbiddenOperationException("没有查询到数据");
        }
        //返回结果
        return PageUtils.toPage(list, AgencyCertificationAuditResDTO.class);
    }

    /**
     * 机构认证申请
     *
     * @param dto
     */
    @Override
    public void submitCertificationAudit(AgencyCertificationAuditAddReqDTO dto) {

        //获取当前登录用户(即机构id)
        Long agencyId = UserContext.currentUserId();
        //保存到机构认证信息表
        //copy dto
        AgencyCertification agencyCertification = BeanUtil.copyProperties(dto, AgencyCertification.class);
        //补齐字段
        agencyCertification.setId(agencyId);
        agencyCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        //调用mapper保存
        AgencyCertification agencyCertification1 = baseMapper.selectById(agencyId);
        if (ObjectUtil.isEmpty(agencyCertification1)){
            baseMapper.insert(agencyCertification);
        }else {
            baseMapper.update(agencyCertification, new QueryWrapper<AgencyCertification>().eq("id", agencyId));
        }
        //保存机构认证审核表
        // copy dto
        AgencyCertificationAudit agencyCertificationAudit = BeanUtil.copyProperties(dto, AgencyCertificationAudit.class);
        //补齐字段
        agencyCertificationAudit.setServeProviderId(agencyId);
        //设置审核状态初始值 未审核(0 未审核 1 已审核)
        agencyCertificationAudit.setAuditStatus(0);
        //设置认证状态
        agencyCertificationAudit.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        //调用mapper保存
        agencyCertificationAuditMapper.insert(agencyCertificationAudit);
    }

    /**
     * 根据机构id更新
     *
     * @param agencyCertificationUpdateDTO 机构认证更新模型
     */
    @Override
    public void updateByServeProviderId(AgencyCertificationUpdateDTO agencyCertificationUpdateDTO) {
        LambdaUpdateWrapper<AgencyCertification> updateWrapper = Wrappers.<AgencyCertification>lambdaUpdate()
                .eq(AgencyCertification::getId, agencyCertificationUpdateDTO.getId())
                .set(AgencyCertification::getCertificationStatus, agencyCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getName()), AgencyCertification::getName, agencyCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getIdNumber()), AgencyCertification::getIdNumber, agencyCertificationUpdateDTO.getIdNumber())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonName()), AgencyCertification::getLegalPersonName, agencyCertificationUpdateDTO.getLegalPersonName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonIdCardNo()), AgencyCertification::getLegalPersonIdCardNo, agencyCertificationUpdateDTO.getLegalPersonIdCardNo())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getBusinessLicense()), AgencyCertification::getBusinessLicense, agencyCertificationUpdateDTO.getBusinessLicense())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getCertificationTime()), AgencyCertification::getCertificationTime, agencyCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }


}
